package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    //登录请求
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        //1.调用业务方法
        R<Employee> r = employeeService.login(employee);
        //2.判断是否登录成功,成功就写入session
        if (r.getCode() == 1) {
            session.setAttribute("employee",r.getData().getId());
        }

     return r;

    }

    //退出请求
    @RequestMapping("/logout")
    public R<String> logout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");

    }

    //处理添加员工的方法
    @PostMapping
    public R<String> save(@RequestBody Employee employee,HttpSession session){
        //获取登录数据中储存的ID
        Long id = (Long) session.getAttribute("employee");
        //完善数据
        //创建人
        employee.setCreateUser(id);
        //修改人
        employee.setUpdateUser(id);
        //调用业务
        employeeService.save(employee);

        return R.success("添加成功");

    }
    //处理分页查询
    @RequestMapping("/page")
    public R<Page<Employee>> findByPage(Integer page,Integer pageSize, String name ){
        Page<Employee> pageObj = employeeService.findByPage(page, pageSize, name);
        return R.success(pageObj);
    }

    //处理跟新员工的请求
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){
        //1.获取当前操作人id
        Long id = (Long) session.getAttribute("employee");
        //2.完善个人资料 条用employee
        employee.setUpdateUser(id);
        //3.调用业务修稿方法
        employeeService.update(employee);

        return R.success("修改成功");


    }
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id){
        R<Employee> r = employeeService.findById(id);
        return r;
    }

}
